Python Basics

Variables

A variable is a name that refers to a value.

a = 10
print(a)
10

The most basic built-in data types that we’ll need to know about are integers, floats, strings, and booleans.

list_example = [10, 1.23, "like this", True, None]
print(list_example)
type(list_example)
[10, 1.23, 'like this', True, None]
list

Booleans and Conditions

Boolean data have either True or False value.

Conditions are expressions that evaluate as booleans.

20 == '20'
False

Existing booleans can be combined, which create a boolean when executed.

x = 4.0
y = .5
z = 3*y - x

x < y or 3*y < x
True
boolean_condition1 = 10 == 20
print(boolean_condition1)

boolean_condition2 = 10 == '10'
print(boolean_condition2)
False
False

The real power of conditions comes when we start to use them in more complex examples, such as if statements.

name = "Geneseo"
score = 99

if name == "Geneseo" and score > 90:
    print("Geneseo, you achieved a high score.")

if name == "Geneseo" or score > 90:
    print("You could be called Geneseo or have a high score")

if name != "Geneseo" and score > 90:
    print("You are not called Geneseo and you have a high score")
Geneseo, you achieved a high score.
You could be called Geneseo or have a high score

The if-else chain:

score = 98

if score == 100:
    print("Top marks!")
elif score > 90 and score < 100:
    print("High score!")
elif score > 10 and score <= 90:
    pass
else:
    print("Better luck next time.")
High score!

For Loops

A loop is a way of executing a similar piece of code over and over in a similar way. The most useful type is for loops.

name_list = ["Ben", "Chris", "Kate", "Mary"]

for name in name_list:
    print(name)
Ben
Chris
Kate
Mary

Dictionaries

A dictionary maps one set of variables to another (one-to-one or many-to-one).

cities_to_temps = {"Paris": 28, "London": 22, "Seville": 36, "Wellesley": 29}

cities_to_temps.keys()
cities_to_temps.values()
cities_to_temps.items()
dict_items([('Paris', 28), ('London', 22), ('Seville', 36), ('Wellesley', 29)])

Running on Empty

Creating empty containers is useful when creating loops. The commands to create empty lists, tuples, dictionaries, and sets are lst = [], tup=(), dic={}, and st = set() respectively.

Slicing Methods

We can extract a substring (a part of a string) from a string by using a slice.

letters = 'abcdefghij'
letters[:]
'abcdefghij'
letters = 'abcdefghij'
letters[4:]
letters[2:]
letters[-3:]
letters[-50:]
'abcdefghij'
letters = 'abcdefghij'
letters[2:5]
letters[-26:-24]
letters[35:37]
''

We can extract a single value from a list by specifying its index:

suny = ['Geneseo', 'Brockport', 'Oswego', 'Binghamton',
        'Stony Brook', 'New Paltz']
suny[0]
suny[1]
suny[2]
'Oswego'

Example from Classwork 4.3:

fare = "$10.00"
tip = "2.00$"
tax = "$ 0.80"
total = fare[0:2] + tip[0] + tax[3:6]
print("The total trip cost is:", total)
The total trip cost is: $12.80

Functions, Arguments, Parameters

A function can take any number and type of input parameters and return any number and type of output results.

print("Cherry", "Strawberry", "Key Lime")
print("Cherry", "Strawberry", "Key Lime", sep = "!")
print("Cherry", "Strawberry", "Key Lime", sep=" ")
Cherry Strawberry Key Lime
Cherry!Strawberry!Key Lime
Cherry Strawberry Key Lime

A function can accept inputs called arguments.

A parameter is an expected function argument.

Example from Classwork 4.4:

list_variable = [100,144,169,1000,8]
x =max(list_variable)
print('The largest value in the list is:',x)
The largest value in the list is: 1000

Installing Modules, Packages, and Libraries

To install a module module_name on your Google Colab, run:

!pip install module_name

From Classwork 4.5: Import the pandas library as pd. Install the itables package. From itables, import the functions init_notebook_mode and show.

import pandas as pd
!pip install itables
from itables import init_notebook_mode
from itables import show
Collecting itables
  Downloading itables-1.7.0-py3-none-any.whl (200 kB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 0.0/200.9 kB ? eta -:--:--     ━━━━━━━━━━━━━━╺━━━━━━━━━━━━━━━━━━━━━━━━━ 71.7/200.9 kB 1.9 MB/s eta 0:00:01     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 200.9/200.9 kB 2.9 MB/s eta 0:00:00
Requirement already satisfied: IPython in /usr/local/lib/python3.10/dist-packages (from itables) (7.34.0)
Requirement already satisfied: pandas in /usr/local/lib/python3.10/dist-packages (from itables) (1.5.3)
Requirement already satisfied: numpy in /usr/local/lib/python3.10/dist-packages (from itables) (1.25.2)
Requirement already satisfied: setuptools>=18.5 in /usr/local/lib/python3.10/dist-packages (from IPython->itables) (67.7.2)
Collecting jedi>=0.16 (from IPython->itables)
  Downloading jedi-0.19.1-py2.py3-none-any.whl (1.6 MB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 1.6/1.6 MB 7.3 MB/s eta 0:00:00
Requirement already satisfied: decorator in /usr/local/lib/python3.10/dist-packages (from IPython->itables) (4.4.2)
Requirement already satisfied: pickleshare in /usr/local/lib/python3.10/dist-packages (from IPython->itables) (0.7.5)
Requirement already satisfied: traitlets>=4.2 in /usr/local/lib/python3.10/dist-packages (from IPython->itables) (5.7.1)
Requirement already satisfied: prompt-toolkit!=3.0.0,!=3.0.1,<3.1.0,>=2.0.0 in /usr/local/lib/python3.10/dist-packages (from IPython->itables) (3.0.43)
Requirement already satisfied: pygments in /usr/local/lib/python3.10/dist-packages (from IPython->itables) (2.16.1)
Requirement already satisfied: backcall in /usr/local/lib/python3.10/dist-packages (from IPython->itables) (0.2.0)
Requirement already satisfied: matplotlib-inline in /usr/local/lib/python3.10/dist-packages (from IPython->itables) (0.1.6)
Requirement already satisfied: pexpect>4.3 in /usr/local/lib/python3.10/dist-packages (from IPython->itables) (4.9.0)
Requirement already satisfied: python-dateutil>=2.8.1 in /usr/local/lib/python3.10/dist-packages (from pandas->itables) (2.8.2)
Requirement already satisfied: pytz>=2020.1 in /usr/local/lib/python3.10/dist-packages (from pandas->itables) (2023.4)
Requirement already satisfied: parso<0.9.0,>=0.8.3 in /usr/local/lib/python3.10/dist-packages (from jedi>=0.16->IPython->itables) (0.8.3)
Requirement already satisfied: ptyprocess>=0.5 in /usr/local/lib/python3.10/dist-packages (from pexpect>4.3->IPython->itables) (0.7.0)
Requirement already satisfied: wcwidth in /usr/local/lib/python3.10/dist-packages (from prompt-toolkit!=3.0.0,!=3.0.1,<3.1.0,>=2.0.0->IPython->itables) (0.2.13)
Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.10/dist-packages (from python-dateutil>=2.8.1->pandas->itables) (1.16.0)
Installing collected packages: jedi, itables
Successfully installed itables-1.7.0 jedi-0.19.1